package com.zzptc.syl.traffic;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Weather extends AppCompatActivity {
    private static final String TAG = "Weather";
    private ArrayList<Fragment> life;
    private ViewPager viewPager;
    private LineChart line;
    private TextView change;
    private LifeIndex data;
    private TextView purple;
    private TextView cold;
    private TextView clothes;
    private TextView sport;
    private TextView bianhua;
    private Timer timer,ti;
    private Button atmosphere;
    private Button qbt;
    private Button abt;
    private Button zbt;
    private int i=0;
    private int q=0;
    private int k=0;
    private Integer[] max=new Integer[2];
    private final Retrofit retrofit=new Retrofit.Builder()
            .baseUrl("http://hh1.me:5001/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    List<Entry> list=new ArrayList<>();
    List<Entry> list2=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        change=findViewById(R.id.change_tview);
        purple=findViewById(R.id.index_tv);
        cold=findViewById(R.id.cold_tv2);
        line = (LineChart) findViewById(R.id.line_chart);
        clothes=findViewById(R.id.clothes_tv);
        bianhua=findViewById(R.id.bianhua_tv);
        sport=findViewById(R.id.sport_tv);
        atmosphere=findViewById(R.id.atmosphere_bt);
        qbt=findViewById(R.id.q_bt);
        abt=findViewById(R.id.a_bt);
        zbt=findViewById(R.id.z_bt);
        viewPager = findViewById(R.id.vpager_weather);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(new WeatherFragment());
        fragments.add(new Weather1Fragment());
        fragments.add(new Weather2Fragment());
        fragments.add(new Weather3Fragment());
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, fragments);
        viewPager.setAdapter(myPagerAdapter);
        timer = new Timer();
        ti = new Timer();
        TimerTask tm=new TimerTask() {
            @Override
            public void run() {
                if (list.size()>7){
                    ti.cancel();
                }
                weathersection();
            }
        };
        ti.schedule(tm,0,1000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                sport();
                purpleIndex();
                clothes();
                cold();
                temperature();
            }
        },0,3000);
        life=new ArrayList<>();
        life.add(new WeatherFragment());
        atmosphere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0,true);
            }
        });
        qbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1,true);
            }
        });
        abt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(2,true);
            }
        });
        zbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(3,true);
            }
        });
        }

    private void weathersection(){
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                Log.d(TAG, "onResponse: "+data.get温度());
                if (i%2==0){
                    max[0]=data.get温度();
                }else {
                    max[1]=data.get温度();
                    if (max[0]>max[1]){
                        getxAxis(max[0],max[1]);
                        bianhua.setText("今天："+max[1]+"-"+max[0]);
                    }else {
                        getxAxis(max[1],max[0]);
                        bianhua.setText("今天："+max[0]+"-"+max[1]);
                    }
                }
//                        list2.add(new Entry(i,data.get温度()-10));
                i++;
//                        getxAxis();
//                        XAxis xAxis = getxAxis();
//                        cylinder(xAxis);
            }
            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {
                Log.d(TAG, "onFailure: "+t.getMessage());
            }
        });
    }

    private void sport() {
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                Log.d(TAG, "onResponse: "+data.get温度());
                sport.setText(String.valueOf(data.getCo2()));
                if (data.getCo2()<3000){
                    sport.setText("     适宜\n  气候适宜，推荐您进行户外运动");
                }if (data.getCo2()<=6000){
                    sport.setText("     中\n  易感人群应适当减少室外活动");
                } else {
                    sport.setText("     较不宜\n  空气氧气含量低，请在室内进行休闲运动");
                }
                k++;
            }
            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {

            }
        });
    }

    private void clothes(){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                clothes.setText(String.valueOf(data.get温度()));
                if (data.get温度()<15){
                    clothes.setText("     冷\n  建议穿长袖衬衫、单裤等服装");
                }if (data.get温度()<=25 && data.get温度()>=15){
                    clothes.setText("     舒适\n  建议穿短袖衬衫、单裤等服装");
                } else {
                    clothes.setText("     热\n  适合穿T恤、短薄外套等夏季服装");
                }
            }
            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {

            }
        });
    }

    private void cold() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                cold.setText(String.valueOf(data.get温度()));
                if (data.get温度()<10){
                    cold.setText("     较易发\n  温度低，风较大，较易发生感冒，注意防护");
                }else {
                    cold.setText("     少发\n  无明显降温，感冒机率较低");
                }
                Toast.makeText(Weather.this, "数据发生变化", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {

            }
        });
    }

    private void purpleIndex() {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                purple.setText(String.valueOf(data.get紫外线强度()));
                if (data.get紫外线强度()<1000){
                    purple.setText("     弱\n  涂擦SPF12~15、PA+护肤品");
                }if (data.get紫外线强度()<=3000 && data.get紫外线强度()>=1000){
                    purple.setText("     中等\n  涂擦SPF大于15、PA+防晒护肤品");
                }else {
                    purple.setText("     强\n  尽量减少外出，需要涂抹高倍数防晒霜");
                }
            }
            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {

            }
        });
    }



    private void getxAxis(int max,int min) {
        list.add(new Entry(i/2,max));
        list2.add(new Entry(i/2,min));

        LineDataSet lineDataSet=new LineDataSet(list,"夜间温度");
        lineDataSet.setColor(Color.RED);  //折线的颜色
        lineDataSet.setLineWidth(2);        //折线的粗细
        lineDataSet.setDrawCircleHole(false);//实心圆
        LineDataSet lineDataSet2=new LineDataSet(list2,"白天温度");
        lineDataSet2.setColor(Color.BLUE);
        lineDataSet2.setLineWidth(2);
        lineDataSet2.setDrawCircleHole(true);
        //添加第二组数据
        LineData lineData=new LineData(lineDataSet);
        lineData.addDataSet(lineDataSet2);
        line.setData(lineData);
        //简单美化
        //   X轴所在位置   默认为上面
        line.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        line.getDescription().setEnabled(false);
        line.getXAxis().setDrawGridLines(false);
        //隐藏右边的Y轴
        line.getAxisRight().setEnabled(false);
        line.invalidate();
        XAxis xAxis=line.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {   //X轴自定义坐标
            @Override
            public String getFormattedValue(float l, AxisBase axisBase) {
                for (int i=1;i<=7;i++){
                    if (l==i){
                        return "星期"+i;
                    }
                }return "";//注意这里需要改成 ""
            }
        });
        xAxis.setAxisMaximum(8);   //X轴最大数值
        xAxis.setAxisMinimum(1);   //X轴最小数值
        line.invalidate();
    }

    private void temperature() {
        Service service=retrofit.create(Service.class);
        Call<LifeIndex> life=service.life();
        life.enqueue(new Callback<LifeIndex>() {
            @Override
            public void onResponse(Call<LifeIndex> call, Response<LifeIndex> response) {
                data=response.body();
                change.setText(String.valueOf(data.get温度()+"℃"));
            }

            @Override
            public void onFailure(Call<LifeIndex> call, Throwable t) {

            }
        });
    }

}